﻿<%@ WebHandler Language="C#" Class="ZSCompleteReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 装配试车厂完工报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.11.24
 **/

public class ZSCompleteReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getQuerySql(JObject jObject)
    {
        string sql = @"
SELECT ep.mfgordername,ep.ordertypename,ep.attributevalue,ep.productname,ep.productfamilyname,ep.factorystardate,ep.factorycompletiondate,
       Max(ep.finishdate) finishdate,ep.earlyDays,ep.overDays,ep.scfinishdate,ep.zpfinishdate
FROM
(
    SELECT mfg.mfgordername,ot.ordertypename,u.attributevalue,pb.productname,pf.productfamilyname,mfg.factorystardate,mfg.factorycompletiondate,ep.finishdate,
           NVL(abs(DECODE(SIGN(trunc(ep.finishdate)-trunc(mfg.factorycompletiondate)),-1,TRUNC(ep.finishdate)-trunc(mfg.factorycompletiondate),NULL)),0) earlyDays,
           CASE WHEN trunc(ep.finishdate)-trunc(mfg.factorycompletiondate) < 0 THEN 0 ELSE trunc(ep.finishdate)-trunc(mfg.factorycompletiondate) END overDays,
           sc.finishdate scfinishdate,zz.finishdate zpfinishdate
    FROM enginepartplan ep
    LEFT JOIN mfgorder mfg ON mfg.mfgorderid = ep.mfgorderid
    LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
    LEFT JOIN productbase pb1 ON pb1.productbaseid = mfg.productbaseid
    LEFT JOIN product p ON p.productid = NVL(pb1.revofrcdid,mfg.productid)
    LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
    LEFT JOIN Ordertype ot ON ot.ordertypeid = mfg.ordertypeid
    LEFT JOIN productworkflowmapping pm ON p.productid=pm.productid
    LEFT JOIN Workflowproductfamilylist wpf ON wpf.workflowid = pm.workflowid
    LEFT JOIN productfamily pf ON wpf.productfamilylistid = pf.productfamilyid
    LEFT JOIN ( SELECT ep.mfgorderid,MAX(ep.finishdate) finishdate 
                FROM enginepartplan ep
                LEFT JOIN workflowstep wfs ON ep.workflowstepid=wfs.workflowstepid
                WHERE ep.type = 1 AND wfs.workflowstepname LIKE '%检验试车%' AND ep.usecompleted='1'
                GROUP BY ep.mfgorderid) sc ON sc.mfgorderid = ep.mfgorderid 
    LEFT JOIN ( SELECT ep.mfgorderid,MAX(ep.finishdate) finishdate 
                FROM enginepartplan ep
                LEFT JOIN workflowstep wfs ON ep.workflowstepid=wfs.workflowstepid
                WHERE ep.type = 1 AND wfs.workflowstepname LIKE '%总装%' AND ep.usecompleted='1'
                GROUP BY ep.mfgorderid ) zz ON zz.mfgorderid = ep.mfgorderid
    WHERE ep.type = 1 AND ep.productid = p.productid AND ep.completestepid IS NOT NULL AND ep.usecompleted = 1 AND ep.completestepid = ep.workflowstepid ";

        //计划开工日期
        if (jObject["planstartdate"] != null && jObject["planstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["planstartdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(mfg.factorystardate) >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(mfg.factorystardate) <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //计划完工日期
        if (jObject["planfinishdate"] != null && jObject["planfinishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["planfinishdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(mfg.factorycompletiondate) >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(mfg.factorycompletiondate) <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND u.attributevalue = '{0}'", jObject["engineno"].ToString());
        }

        //订单类型
        if (jObject["ordertypename"] != null && jObject["ordertypename"].ToString() != "")
        {
            sql += string.Format(" AND ot.ordertypename = '{0}'", jObject["ordertypename"].ToString());
        }

        //型别
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND pf.productfamilyname = '{0}'", jObject["productfamilyname"].ToString());
        }

        sql += @"
    UNION ALL 
    SELECT mfg.mfgordername,ot.ordertypename,u.attributevalue,pb.productname,pf.productfamilyname,mfg.factorystardate,mfg.factorycompletiondate,te.finishdate,  
           NVL(abs(DECODE(SIGN(trunc(te.finishdate)-trunc(mfg.factorycompletiondate)),-1,TRUNC(te.finishdate)-trunc(mfg.factorycompletiondate),NULL)),0) earlyDays,
           CASE WHEN trunc(te.finishdate)-trunc(mfg.factorycompletiondate) < 0 THEN 0 ELSE trunc(te.finishdate)-trunc(mfg.factorycompletiondate) END overDays,
           NULL AS scfinishdate,NULL AS zpfinishdate
    FROM
    (
      SELECT ep.mfgorderid,u.attributevalue,MAX(ep.finishdate) finishdate
      FROM enginepartplan ep
      LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
      WHERE ep.type <> 1
      HAVING SUM(ep.usecompleted) = COUNT(1)
      GROUP BY ep.mfgorderid,u.attributevalue
    ) te
    LEFT JOIN mfgorder mfg ON mfg.mfgorderid = te.mfgorderid
    LEFT JOIN Userattribute u ON u.parentid = mfg.mfgorderid AND u.userattributename='发动机'
    LEFT JOIN productbase pb1 ON pb1.productbaseid = mfg.productbaseid
    LEFT JOIN product p ON p.productid = NVL(pb1.revofrcdid,mfg.productid)
    LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
    LEFT JOIN Ordertype ot ON ot.ordertypeid = mfg.ordertypeid
    LEFT JOIN productworkflowmapping pm ON p.productid=pm.productid
    LEFT JOIN Workflowproductfamilylist wpf ON wpf.workflowid = pm.workflowid
    LEFT JOIN productfamily pf ON wpf.productfamilylistid = pf.productfamilyid
    WHERE 1=1 ";
        //计划开工日期
        if (jObject["planstartdate"] != null && jObject["planstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["planstartdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(mfg.factorystardate) >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(mfg.factorystardate) <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //计划完工日期
        if (jObject["planfinishdate"] != null && jObject["planfinishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["planfinishdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND TRUNC(mfg.factorycompletiondate) >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(mfg.factorycompletiondate) <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND u.attributevalue = '{0}'", jObject["engineno"].ToString());
        }

        //订单类型
        if (jObject["ordertypename"] != null && jObject["ordertypename"].ToString() != "")
        {
            sql += string.Format(" AND ot.ordertypename = '{0}'", jObject["ordertypename"].ToString());
        }

        //型别
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND pf.productfamilyname = '{0}'", jObject["productfamilyname"].ToString());
        }
        sql += @"
) ep
GROUP BY ep.mfgordername,ep.ordertypename,ep.attributevalue,ep.productname,ep.productfamilyname,ep.factorystardate,ep.factorycompletiondate,
         ep.earlyDays,ep.overDays,ep.scfinishdate,ep.zpfinishdate
ORDER BY ep.mfgordername,ep.ordertypename,ep.attributevalue
";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();
        string sql = getQuerySql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);

        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["mfgordername"].Caption = "生产订单号";
        dt.Columns["ordertypename"].Caption = "任务类型";
        dt.Columns["attributevalue"].Caption = "发动机号";
        dt.Columns["productname"].Caption = "物料号";
        dt.Columns["productfamilyname"].Caption = "型别";
        dt.Columns["zpfinishdate"].Caption = "装配完成日期";
        dt.Columns["scfinishdate"].Caption = "试车完成日期";
        dt.Columns["factorystardate"].Caption = "计划开工日期";
        dt.Columns["factorycompletiondate"].Caption = "计划完工日期";
        dt.Columns["finishdate"].Caption = "实际完工日期";
        dt.Columns["earlydays"].Caption = "提前完工天数";
        dt.Columns["overdays"].Caption = "超期天数";
        ExportHelper.ExportExcel(dt, jObject["factoryname"].ToString() + "完工报表");
    }
}